package org.example.service.impl;

import org.example.config.ResponseResult;
import org.example.pojo.DataSourceConfigDto;
import org.example.service.DatasourceService;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static com.fasterxml.jackson.databind.type.LogicalType.Map;

/**
 * @author wxm
 * @date 2025/3/7 8:02
 */
@Service
public class DatasourceServiceImpl implements DatasourceService {
    @Override
    public ResponseResult<?> testConnection(DataSourceConfigDto config) {
        // 1. 参数校验
        if (config.getHost() == null || config.getPort() == null) {
            return ResponseResult.fail(500,"主机和端口不能为空");
        }
        // 2. 构建JDBC URL
        String url = buildJdbcUrl(config);
        // 3. 尝试连接
        try (Connection conn = DriverManager.getConnection(url, config.getUsername(), config.getPassword())) {
            return ResponseResult.success("连接成功");
        } catch (SQLException e) {
            String errorMsg = parseSqlException(e);
            return ResponseResult.fail(500, errorMsg);
        }
    }

    private String buildJdbcUrl(DataSourceConfigDto config) {
        switch (config.getDbType().toLowerCase()) {
            case "mysql":
                return String.format("jdbc:mysql://%s:%d/%s?serverTimezone=UTC",
                        config.getHost(), config.getPort(), config.getDatabase());
            case "dm":
                return String.format("jdbc:dm://%s:%d/%s?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8",
                        config.getHost(), config.getPort(), config.getDatabase());
            default:
                throw new IllegalArgumentException("不支持的数据库类型");
        }
    }

    private String parseSqlException(SQLException e) {
        // 根据错误码或状态判断具体原因
        if (e.getErrorCode() == 1045) { // MySQL访问拒绝
            return "用户名或密码错误";
        } else if (e.getSQLState().startsWith("08")) { // 连接错误
            return "网络连接失败，请检查主机和端口";
        }
        return "数据库连接异常：" + e.getMessage();
    }
}
